import React, { useEffect, useState } from "react";
import { useNavigate } from 'react-router-dom';
import { Menu, Layout } from 'antd';
import * as IconMould from "@ant-design/icons";
import { useDispatch } from 'react-redux';
import { setTagList } from '@store/reducers/MenuSlice';
import Routers from "@src/config";

const SiderComponents = ({ CollapseStart }) => {
  const { Sider } = Layout;
  const navigate = useNavigate();
  const dispatch = useDispatch();

  const [routerData, setRouterData] = useState([]);

  useEffect(() => {
    const cachedRouters = localStorage.getItem('menu');
    if (cachedRouters) {
      setRouterData(JSON.parse(cachedRouters));
    } else {
      setRouterData(Routers);
    }
  }, []);

  const IconItems = (name) => React.createElement(IconMould[name]);

  const RoutersItems = routerData.map((item) => {
    const child = {
      key: item.path,
      icon: IconItems(item.icon),
      label: item.label,
    };

    if (item.children) {
      child.children = item.children.map((childItem) => ({
        key: childItem.path,
        label: childItem.label,
      }));
    }

    return child;
  });

  const SeltMenu = (e) => {
    window.sessionStorage.setItem('DefaultSelectedKeys', e.key);
    let data;

    routerData.forEach((element) => {
      if (element.path === e.keyPath[e.keyPath.length - 1]) {
        data = element;

        if (e.keyPath.length > 1) {
          data = element.children?.find((child) => child.path === e.key);
        }
      }
    });

    if (data) {
      dispatch(setTagList({
        path: data.path,
        name: data.name,
        label: data.label,
      }));
    }

    navigate(e.key);
  };

  const SetTagList = (val) => {
    dispatch(setTagList(val));
  };

  return (
    <div>
      <Sider id="Sider" trigger={null} collapsible collapsed={CollapseStart}>
        <h2 className="app_name margin_bottom_clear">
          {CollapseStart ? '' : 'Forever丿顾北'}
        </h2>
        <Menu
          id="Menu"
          theme="dark"
          mode="inline"
          defaultSelectedKeys={
            window.sessionStorage.getItem('DefaultSelectedKeys')
              ? [window.sessionStorage.getItem('DefaultSelectedKeys')]
              : [RoutersItems[0]?.key || '']
          }
          items={RoutersItems}
          onClick={SeltMenu}
        />
      </Sider>
    </div>
  );
};

export default SiderComponents;